/*!
 homepage.js
 */

$.fn.countTo = function(options) {
  options = options || {};

  return $(this).each(function() {
    var settings = $.extend({}, $.fn.countTo.defaults, {
      from: $(this).data('from'),
      to: $(this).data('to'),
      speed: $(this).data('speed'),
      refreshInterval: $(this).data('refresh-interval'),
      decimals: $(this).data('decimals')
    }, options);
    var loops = Math.ceil(settings.speed / settings.refreshInterval),
      increment = (settings.to - settings.from) / loops;
    var self = this,
      $self = $(this),
      loopCount = 0,
      value = settings.from,
      data = $self.data('countTo') || {};

    $self.data('countTo', data);
    if (data.interval) {
      clearInterval(data.interval);
    }
    data.interval = setInterval(updateTimer, settings.refreshInterval);
    render(value);

    function updateTimer() {
      value += increment;
      loopCount++;
      render(value);
      if (typeof(settings.onUpdate) === 'function') {
        settings.onUpdate.call(self, value);
      }
      if (loopCount >= loops) {
        $self.removeData('countTo');
        clearInterval(data.interval);
        value = settings.to;
        if (typeof(settings.onComplete) === 'function') {
          settings.onComplete.call(self, value);
        }
      }
    }

    function render(value) {
      var formattedValue = settings.formatter.call(self, value, settings);
      $self.html(formattedValue);
    }
  })
}

$.fn.countTo.defaults = {
  from: 0,
  to: 0,
  speed: 1000,
  refreshInterval: 100,
  decimals: 0,
  formatter: formatter,
  onUpdate: null,
  onComplete: null
}

function formatter(value, settings) {
  return value.toFixed(settings.decimals)
}

layui.define(['carousel', 'Http', 'setter', 'view'], function(e) {

  var carousel = layui.carousel
  var Http = layui.Http
  var setter = layui.setter
  var view = layui.view

  var $willCnt = $('[layadmin-event="will"]').find('.count')
  var $doneCnt = $('[layadmin-event="done"]').find('.count')
  var $history = $('#home-page-history')

  var routes = []
  var limit = setter.historyMax
  var routeKey = 'AppRoutes'

  var callback = function($target, response) {
    var data = response.data
    $target
      .attr('data-to', data.count)
      .attr('data-speed', 1500)
      .countTo({})
  }

  var getCount = function(ajaxSettings, type) {
    var Href = {
      will: '/waiteHandlerController/getWorkflowCountAll4LoginUser.htm',
      warning: '/warningController/getMyEarlyWarningCount.json',
      done: '/wfFinished/getWorkflowFinishedCountAllLoginUser.htm'
    }

    var _options = {
      type: 'post',
      url: Href[type],
      ifModified: true,
      contentType: 'application/json;charset=UTF-8'
    }

    if ($.isFunction(ajaxSettings)) {
      _options.success = ajaxSettings
    } else {
      $.extend(_options, ajaxSettings)
    }

    if (!_options.url) {
      return false
    }

    return new Http(_options).fetch()
  }

  var showHistory = function(routes) {
    var _html = ''

    App.util.setStore(routeKey, routes)
    for (var i = routes.length - 1; i >= 0; --i) {
      var option = routes[i]
      _html += '<li data-id="' + option.id + '" data-url="' + option.url + '" data-tip="' + option.tip +'" data-text="' + option.text + '">' +
        '<div><span class="left">' + option.text + '</span>' +
        '<span class="right">' + App.util.cut(option.tip, 22) + '</span></div>' +
        '</li>'
    }
    $history.html(_html)
  }

  var promise1 = getCount(function(response) {
    callback($willCnt, response)
  }, 'will')

  promise1.always(function() {
    getCount(function(response) {
      callback($doneCnt, response)
    }, 'done')
  })

  try {
    routes = JSON.parse(App.util.getStore(routeKey)) || []
  } catch (_) {}

  routes = routes.slice(0, limit)
  showHistory(routes)

  view('LAY_homepage-system').render('version', top.layui.admin || {v: '4.0.0'})

  carousel.render({
    elem: '#test1',
    width: '100%',
    arrow: 'none',
    interval: 2 * 60 * 1000,
    autoplay: false,
    trigger: 'hover'
  })

  layui.onevent('admin', 'admin(history)', function(option) {
    // console.log(option.text)
    routes.unshift(option)
    routes.length > limit && routes.pop()
    showHistory(routes)
  })

  $('[layadmin-event]').on('click', function() {
    var $this = $(this)
    var frame = top.frame
    var event = $this.attr('layadmin-event')
    var calls = {
      will: function() {
        var will = frame.cache.tab_will
        frame.openTab(will)
      },
      done: function() {
        var done = frame.cache.tab_done
        frame.openTab(done)
      },
      watch: function() {
        frame.openTab({
          url: 'druid/index.html',
          text: '数据监控',
          id: 'druid'
        })
      },
      cache: function() {
        frame.openTab({
          url: 'v1/cacheIndex',
          text: '缓存配置',
          id: 'cache'
        })
      },
      warning: function() {
        var cache = frame.cache
        frame.openTab(cache.tab_warning)
      },
      set: function() {
        frame.openTab({
          id: 'frame-set',
          text: '设置',
          url: 'common/goSet.htm'
        })
      },
      clearHistory: function() {
        App.util.removeStore(routeKey)
        $history.html('')
        layer.alert('清除成功')
      }
    }
    jQuery.isFunction(calls[event]) && calls[event].apply(this)
  })

  $history.on('click', 'li', function() {
    var $this = $(this)
    var frame = top.frame
    var opt = {
      id: $this.data('id'),
      url: $this.data('url'),
      text: $this.data('text'),
      tip: $this.data('tip')
    }
    frame.openTab(opt)
  })

  e('homepage', {})
})
